package top.lyc829.mymusic.ui.fragment.login.phone

import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import top.lyc829.mymusic.R
import top.lyc829.mymusic.base.BaseFragment
import top.lyc829.mymusic.databinding.FragmentPhoneLoginBinding
import top.lyc829.mymusic.ext.dismissLoading
import top.lyc829.mymusic.ext.showLoading
import top.lyc829.mymusic.ext.showToast
import top.lyc829.mymusic.util.ValidateUtils

class PhoneLoginFragment : BaseFragment<PhoneLoginViewModel, FragmentPhoneLoginBinding>() {

    companion object {
        fun newInstance() = PhoneLoginFragment()
    }

    override fun getViewModel() = ViewModelProvider(this).get(PhoneLoginViewModel::class.java)

    override fun getBinding(inflater: LayoutInflater) = FragmentPhoneLoginBinding.inflate(inflater)


    override fun initView(savedInstanceState: Bundle?) {
    }

    override fun initClickListener() {

        binding.imgTabBack.setOnClickListener {
            findNavController().navigateUp()
        }

        binding.tvLogin.setOnClickListener {
            val phone = binding.etLoginPhone.text.toString().trim()
            val password = binding.etLoginPassword.text.toString().trim()
            if (!ValidateUtils.isMobile(phone)) {
                showToast("请输入正确的手机号")
            } else if (!ValidateUtils.isPassword(password)) {
                showToast("密码格式错误")
            } else {
                mViewModel.doLogin(phone, password)
            }
        }
    }

    override fun createObserver() {
        mViewModel.loginState.observe(viewLifecycleOwner) {
            if (it) {
                showToast("登录成功")
                findNavController().popBackStack(R.id.mainFragment, true)
            }
        }

        mViewModel.isLoading.observe(viewLifecycleOwner) {
            if (it) showLoading() else dismissLoading()
        }

    }

    override fun initData() {

    }


}